import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useLocaleStore = defineStore('locale', () => {
  // ========== 状态管理 ==========
  
  // 当前语言
  const currentLocale = ref('zh-CN')
  
  // 支持的语言列表
  const supportedLocales = [
    { value: 'zh-CN', label: '简体中文', icon: '🇨🇳' },
    { value: 'en-US', label: 'English', icon: '🇺🇸' },
    { value: 'ja-JP', label: '日本語', icon: '🇯🇵' }
  ]
  
  // ========== 计算属性 ==========
  
  // 当前语言信息
  const currentLocaleInfo = computed(() => {
    return supportedLocales.find(item => item.value === currentLocale.value) || supportedLocales[0]
  })
  
  // ========== 方法 ==========
  
  // 设置语言
  const setLocale = (locale) => {
    if (!supportedLocales.find(item => item.value === locale)) {
      console.warn(`不支持的语言: ${locale}，回退到默认语言`)
      locale = 'zh-CN'
    }
    
    currentLocale.value = locale
    
    // 持久化到 localStorage
    localStorage.setItem('locale', locale)
    
    // 更新 HTML lang 属性
    document.documentElement.setAttribute('lang', locale)
  }
  
  // 初始化语言（从 localStorage 读取）
  const initLocale = () => {
    const stored = localStorage.getItem('locale')
    if (stored && supportedLocales.find(item => item.value === stored)) {
      currentLocale.value = stored
    } else {
      // 尝试从浏览器语言获取
      const browserLang = navigator.language || navigator.userLanguage
      const matched = supportedLocales.find(item => item.value === browserLang)
      currentLocale.value = matched ? browserLang : 'zh-CN'
    }
    
    // 更新 HTML lang 属性
    document.documentElement.setAttribute('lang', currentLocale.value)
  }
  
  // 获取语言标签
  const getLocaleLabel = (locale) => {
    const item = supportedLocales.find(item => item.value === locale)
    return item ? item.label : locale
  }
  
  return {
    // 状态
    currentLocale,
    supportedLocales,
    currentLocaleInfo,
    
    // 方法
    setLocale,
    initLocale,
    getLocaleLabel
  }
})

